package com.stox.downloader.bse;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import com.stox.core.model.Bar;
import com.stox.core.model.Scrip;
import com.stox.core.util.StringUtil;
import com.stox.downloader.DataStreamParser;

public class BseDataStreamParser implements DataStreamParser {

	@Override
	public BseDataStream parse(String rawData) {
		List<Bar> barList = new ArrayList<Bar>();
		if(StringUtil.hasText(rawData)){
			StringTokenizer t = new StringTokenizer(rawData,"\n",false);
			while(t.hasMoreTokens()){
				Bar b = parseString(t.nextToken(), "BO");
				if(b != null){
					barList.add(b);					
				}
			}
		}
		return new BseDataStream(barList);
	}

	public Bar parseString(String str,String exchangeCode){
		Bar bar = new Bar();
		Scrip scrip = new Scrip();
		scrip.setExchangeCode(exchangeCode);
		if(StringUtil.hasText(str)){
			StringTokenizer t = new StringTokenizer(str,",",false);
			try{
				scrip.setCode(t.nextToken());
				scrip.setName(t.nextToken());//bar.setName(t.nextToken());
				scrip.setGroup(t.nextToken().trim().toUpperCase());
				scrip.setType(t.nextToken().trim().toUpperCase());
				if(!"Q".equals(scrip.getType())){
					return null;
				}
				bar.setScrip(scrip);
				
				bar.setScripCode(scrip.getCode());
				bar.setOpen(Double.parseDouble(t.nextToken()));
				bar.setHigh(Double.parseDouble(t.nextToken()));
				bar.setLow(Double.parseDouble(t.nextToken()));
				bar.setClose(Double.parseDouble(t.nextToken()));
				bar.setLast(Double.parseDouble(t.nextToken()));
				bar.setPreviousClose(Double.parseDouble(t.nextToken()));
				bar.setTrades(Double.parseDouble(t.nextToken()));
				bar.setVolume(Double.parseDouble(t.nextToken()));
				bar.setTurnover(Double.parseDouble(t.nextToken()));
			}catch(NumberFormatException nfe){
				bar = null;
			}catch(Exception e){
				e.printStackTrace();
				bar = null;
			}
		}
		
		return bar;
	}
	
	
	
}
